//
//  CCQOAuthViewController.swift
//  NEWweibo
//
//  Created by 神威 on 16/9/21.
//  Copyright © 2016年 ccq. All rights reserved.
//

import UIKit
import SVProgressHUD
//  第三方登录视图控制器
//  新浪开发平台提供的APPKey
let WeiboAppKey = "2577445831"
let WeiboAppSecret = "c0667ad40f4b2168d7e49efd48956b6a"
//  授权回调页
let WeiboRedirect_Uri = "http://www.itcast.cn"
class CCQOAuthViewController: UIViewController {
    
    //懒加载
    private lazy var webView: UIWebView = UIWebView()
    
    //  重写loadView, 目的把webView作为视图控制器的view
    override func loadView() {
        
        //  解决底部webView黑条
        //  改成透明解决黑条问题
        webView.isOpaque = false
        
        //  设置代理
        webView.delegate = self
        
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        requestLogin()
        setupNavUI()

        // Do any additional setup after loading the view.
    }

    //  请求第三方登录
    private func requestLogin() {
        //  准备url地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        
        //  创建urlrequest对象
        let urlRequest = URLRequest(url: URL(string: url)!)
        
        webView.loadRequest(urlRequest)
        
        
        
    }
    
    //  设置导航栏按钮
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        title = "微博"
    }
    
    //  MARK: -- 点击事件处理
    @objc private func cancelAction() {
        
        dismiss(animated: true, completion: nil)
        
    }
    
    @objc private func autoFillAction() {
        
        print("自动填充")
        
        
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '18630628330';document.getElementById('passwd').value = 'dxj930314'")
        
        
        
        
    }
    

    

  
}

extension CCQOAuthViewController:UIWebViewDelegate{
    //  开始加载请求
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //  加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    //  将要加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //  判断url是否合法
        guard let url = request.url else {
            
            print("url 为 nil")
            
            return false
        }
        
        print( url.absoluteString)
        
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            //  表示不是我们关心
            return true
        }
        
        //  代码执行到此表示是是我们关系的请求地址
        //  取到地址栏中的参数
        if let query = url.query , query.hasPrefix("code=") {
            //  根据光标的结束位置获取子串
            let code = query.substring(from: "code=".endIndex)
            //  通过code获取accesstoken
            //requestAccesstoken(code: code)
            
            
            CCQUserAccountViewModel.sharedUserAccountViewModel.requestAccesstoken(code: code, callBack: { (isSuccess) in
                
                if isSuccess {
                    //  表示登录成功
                    print("登录成功")
                    //  要等到dismis完成以后在发送切换根视图控制器的操作
                    self.dismiss(animated: false, completion: {
                        //  进入欢迎页面
                        
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                    })
                    
                    
                    
                    
                    
                    
                }
                
                
            })
            
            
            
        } else {
            //  取消授权
            dismiss(animated: true, completion: nil)
        }
        
        
        
        
        
        return false
        
    }
    
    
    
    
}

